<?php
/**
 * Payment logger.
 * Display invalid payment actions including
 * 1. Delete an paid service
 * 2. Payment actions that were forced to previous day.
 * <br />
 * 
 * @author ptnguyen
 * @package modules.report.includes.paymentLogging
 * @version $Id$
 */
class PaymentLogger {
    
    const REPORT_DAILY = 1;
    const REPORT_BY_DOCTOR = 2;
    
    private $reportType;    
    private $fromDate;
    private $toDate;
    
    private $_db;
    
    private $controller;
    /**
     * @var PaymentLoggerModel 
     */
    private $loggerData;
    
    /**
     * Constructor.
     * 
     * @param $controller Controller rendering the log to HTML 
     * @param $fromDate start date
     * @param $toDate end date     
     */
    function __construct($controller, $fromDate, $toDate) {
        $this->fromDate = $fromDate;
        $this->toDate = $toDate;
        
        $this->loggerData = new PaymentLoggerModel();
        $this->controller = $controller;
        $this->_db = Celini::dbInstance();
    }
    
    /**
     * Set report type to show specified log info.
     * 
     * @param $reportType
     * @return void
     */
    public function setReportType($reportType) {
        if ($reportType == self::REPORT_DAILY ||
                $reportType == self::REPORT_BY_DOCTOR) {
            $this->reportType = $reportType;            
        }                        
    }
    
    /**
     * Build the log model.
     * @return unknown_type
     */
    public function buildLogModel() {
        $sql = "SELECT pay_receipt_log_id, enum_action_type, enum_item_type, pay_receipt_item_id, receipt_code, 
                    service_code, quantity, amount, patient_code, patient_name, doctor_id, doctor_name,                    
                    DATE(date_collect) date_collect, DATE(date_modified) date_modified, user_modified  
                FROM pay_receipt_log
                WHERE DATE(date_collect) >= '$this->fromDate'
                    AND DATE(date_collect) <= '$this->toDate'
                ORDER BY pay_receipt_log_id";
        
        $res = $this->_db->Execute($sql);        
        if ($res !== false) {
            while (!$res->EOF) {
                $this->loggerData->addLogItem(
                array(
                    'pay_receipt_log_id'    => $res->fields['pay_receipt_log_id'],
                    'pay_receipt_item_id'   => $res->fields['pay_receipt_item_id'],
                    'receipt_code'          => $res->fields['receipt_code'],                
                    'enum_action_type'      => $res->fields['enum_action_type'],
                    'enum_item_type'        => $res->fields['enum_item_type'],
                    'service_code'          => $res->fields['service_code'],
                    'quantity'              => $res->fields['quantity'],
                    'amount'                => $res->fields['amount'],
                    'patient_code'          => $res->fields['patient_code'],
                    'patient_name'          => $res->fields['patient_name'],
                    'doctor_id'             => $res->fields['doctor_id'],
                    'doctor_name'           => $res->fields['doctor_name'],
                    'date_collect'          => $res->fields['date_collect'],
                    'date_modified'         => $res->fields['date_modified'],
                    'user_modified'         => $res->fields['user_modified']                    
                )
                );
                $res->MoveNext();
            }
        }        
    }
    
    /**
     * Render logger info by report type
     * @return html
     */
    public function renderLogInfo() {
        switch ($this->reportType) {
            case self::REPORT_DAILY:
                return $this->renderDailyReportActionLog();
            case self::REPORT_BY_DOCTOR:
                return $this->renderDoctorReportActionLog();
        }
         
    }    
    
    /**
     * Render logger infor for daily report
     * @return html
     */
    private function renderDailyReportActionLog() {
        $collectedData = $this->loggerData->getLogData(
               EnumerationConstant::PAYMENT_LOGGING_ACTION_OLD_RECEIPT_KEY);
        $repaidData = $this->loggerData->getLogData(
                EnumerationConstant::PAYMENT_LOGGING_ACTION_REPAID_KEY);
                                        
        $this->controller->assign('invalidCollectedItems', $collectedData);
        $this->controller->assign('invalidRepaidItems', $repaidData);        
        return $this->controller->view->render('action_log.html');                
    }
    
    /**
     * Render logger infor for doctor report
     * @return html
     */
    private function renderDoctorReportActionLog() {
        $deletedData = $this->loggerData->getLogData(
               EnumerationConstant::PAYMENT_LOGGING_ACTION_DELETE_KEY);
        $transferedData = $this->loggerData->getLogData(
                EnumerationConstant::PAYMENT_LOGGING_ACTION_TRANSFER_KEY);
        $this->controller->assign('deletedData', $this->prepareDoctorReportData($deletedData));
        $this->controller->assign('transferedData', $this->prepareDoctorReportData($transferedData));
        return $this->controller->view->render('action_log.html');
    }
    
    private function prepareDoctorReportData($dataArr = array()) {
        
        $XRAY_ACCOUNT        = 'xray';
        $LAB_ACCOUNT         = 'lab';
        
        $XRAY_TITLE          = 'X-quang';
        $LAB_TITLE           = 'Xét nghiệm';
        
        $result = array();
        $temp = array(
            $XRAY_ACCOUNT => array(
                                'doctor_name'   => $XRAY_TITLE,
                                'doctor_num_row'=> 0,
                                'doctor_data'   => array()),
            $LAB_ACCOUNT  => array(
                                'doctor_name'   => $LAB_TITLE,
                                'doctor_num_row'=> 0,
                                'doctor_data'   => array()));
            
        foreach ($dataArr as $item) {
            
            switch ($item['enum_item_type']) {
                case EnumerationConstant::ODON_SERVICE_TYPE_X_RAY_KEY:
                    $temp[$XRAY_ACCOUNT] ['doctor_num_row'] += 1;
                    $temp[$XRAY_ACCOUNT] ['doctor_data'] [] = $item;
                    break;
                case EnumerationConstant::ODON_SERVICE_TYPE_LAB_KEY:
                    $temp[$LAB_ACCOUNT] ['doctor_num_row'] += 1;
                    $temp[$LAB_ACCOUNT] ['doctor_data'] [] = $item;                    
                    break;
                case EnumerationConstant::ODON_SERVICE_TYPE_HIGH_TECH_KEY:
                    $doctorId = $item['doctor_id'];
                    if (isset($temp[$doctorId])) {
                        $temp[$doctorId] ['doctor_num_row'] += 1;
                        $temp[$doctorId] ['doctor_data'] [] = $item;
                    } else {
                        $temp[$doctorId] = array(
                                            'doctor_name' => $item['doctor_name'],
                                            'doctor_num_row' => 1,
                                            'doctor_data' => 
                                                array($item));
                    }
                    break;
            }
                       
        }
        
        
        foreach ($temp as $item) {            
            $size = sizeof($item['doctor_data']);
            if ($size > 0) {
                $result [] = $item;    
            }            
        }        
        return $result;
    }
}


/**
 * Model for payment logging storage.
 * 
 * @author ptnguyen
 * @version $Id$
 *
 */
class PaymentLoggerModel {
    
    private $deletedRows = array();
    private $collectedRows = array();
    private $transferedRows = array();
    private $repaidRows = array();
    
    /**
     * Adding item data to model.
     * 
     * Classify data into group by enum_action_type
     * @param $item
     * @return 
     */
    public function addLogItem($item) {
        switch ($item['enum_action_type']) {
        	case EnumerationConstant::PAYMENT_LOGGING_ACTION_DELETE_KEY:
               $this->deletedRows[] = $item;     	            	
        	   break;
        	   
        	case EnumerationConstant::PAYMENT_LOGGING_ACTION_OLD_RECEIPT_KEY:
        	    $this->collectedRows[] = $item;
        	    break;
        	    
        	case EnumerationConstant::PAYMENT_LOGGING_ACTION_TRANSFER_KEY:
        	    $this->transferedRows[] = $item;
                break;    
                
        	case EnumerationConstant::PAYMENT_LOGGING_ACTION_REPAID_KEY:
        	    $this->repaidRows[] = $item;
        	    break;        	        
        }
    }
    
    
    public function getLogData($type, $getPatientAccount = false) {
        $data = array();
        $forcePatientAccount = false;
        
        switch ($type) {
            case EnumerationConstant::PAYMENT_LOGGING_ACTION_DELETE_KEY:
               $data = $this->deletedRows;                         
               break;
               
            case EnumerationConstant::PAYMENT_LOGGING_ACTION_OLD_RECEIPT_KEY:
                $data = $this->collectedRows;
                $forcePatientAccount = true;                
                break;
                
            case EnumerationConstant::PAYMENT_LOGGING_ACTION_TRANSFER_KEY:
                $data = $this->transferedRows;                
                break;    
                
            case EnumerationConstant::PAYMENT_LOGGING_ACTION_REPAID_KEY:
                $data = $this->repaidRows;
                $forcePatientAccount = true;                
                break;
        }
        
        $result = array();
        if ($forcePatientAccount) {            
            foreach ($data as $item) {                
                $item['amount'] = L10nHelper::renderCurrency($item['amount']);                               
                $result[] = $item;
            }              
        } else {
            foreach ($data as $item) {
                if ($item['doctor_id'] > 0 || 
                    ($item['doctor_id'] == -1 && $getPatientAccount)) {                        
                    $item['amount'] = L10nHelper::renderCurrency($item['amount']);                    
                    $result[] = $item;
                } 
            }
        }
        return $result;
    }
}


















